<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      align-center
      destroy-on-close
      draggable
      @close="closeDialog"
      style="width: 1000px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="105px"
        style="width: 100%"
        class="produce_order_form"
      >
        <!-- 只读状态显示遮罩 -->
        <div v-show="isReadonly" class="formCover"></div>
        <div class="header">
          <span class="title">基本信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工厂" prop="plantId" :rules="rules.plantId">
              <el-select
                v-model="formData.plantId"
                placeholder="请选择工厂"
                clearable
                @change="selectPlant"
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="工作中心"
              prop="workCenterId"
              :rules="rules.workCenterId"
            >
              <el-select
                v-model="formData.workCenterId"
                placeholder="请选择工作中心"
                clearable
                @change="selectWorkCenter"
              >
                <el-option
                  v-for="item in workShopList"
                  :key="item.id"
                  :label="item.workshopName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="工作年"
              prop="planYear"
              :rules="rules.planYear"
            >
              <el-select
                v-model="formData.planYear"
                placeholder="请选择工作年份"
                clearable
                @change="selectYear"
              >
                <el-option
                  v-for="item in yearOptions"
                  :key="item"
                  :value="item"
                  :label="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="工作周"
              prop="planWeek"
              :rules="rules.planWeek"
            >
              <el-select
                v-model="formData.planWeek"
                placeholder="请选择工作周"
                clearable
              >
                <el-option
                  v-for="item in monthOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" /></el-select></el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item
              label="物料/版本号"
              prop="routingAllocationId"
              :rules="rules.routingAllocationId"
            >
              <el-select
                v-model="formData.routingAllocationId"
                placeholder="请选择物料/版本号"
                clearable
              >
                <el-option
                  v-for="item in materialList"
                  :key="item.id"
                  :label="`${item.workCenterCode ?? ''}/${
                    item.versionNo ?? ''
                  }`"
                  :value="item.id"
              /></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="计划数量"
              prop="planQuantity"
              :rules="rules.planQuantity"
            >
              <el-input
                v-model="formData.planQuantity"
                placeholder="请输入计划数量"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="生产批次"
              prop="planBatch"
              :rules="rules.planBatch"
            >
              <el-input
                v-model="formData.planBatch"
                placeholder="请输入生产批次"
                clearable /></el-form-item
          ></el-col>
        </el-row>

        <!-- <el-divider /> -->
        <div class="mt-[10px]">
          <div class="header">
            <span class="title">卷料明细（必选）</span>
            <el-button
              v-show="!isReadonly"
              type="success"
              plain
              small
              @click="handleAdd"
            >
              <i-ep-plus />新增</el-button
            >
          </div>

          <el-table
            :data="formData.plans"
            style="width: 100%"
            :key="Math.random"
            height="244"
            :border="true"
          >
            <el-table-column
              label="序号"
              type="index"
              width="60"
              align="center"
            />
            <el-table-column prop="remarks" label="条码号" align="center" />
            <el-table-column
              prop="remarks"
              label="重量"
              width="100"
              align="right"
            />
            <el-table-column
              prop="remarks"
              label="理论数量"
              width="150"
              align="right"
            />
            <el-table-column
              prop="remarks"
              label="存储类型"
              width="150"
              align="center"
            />
            <el-table-column
              prop="remarks"
              label="货位"
              align="center"
              width="150"
            />
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="140"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-show="!isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="week-produce-order-edit">
import request from "@/utils/request";
import { validateNumber } from "@/utils/commonHooks";
import { getWorkShopsApi } from "@/api/plant/index";
import { getMonthList, getOneLineDate } from "../index";
import { getWeekNumber } from "@/utils/dateUtils";

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "",
  },
  parentTaskId: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: () => {},
  },
  plantList: {
    type: Array,
    default: (): any => [],
  },
  yearOptions: {
    type: Array,
    default: (): any => [],
  },
});

const { plantList, yearOptions } = toRefs(props);

// 选择工厂
function selectPlant(e: string) {
  getWorkShopList(e);
}

// 工作中心列表
const workShopList: any = ref([]);
const getWorkShopList = async (id: string) => {
  formData.workCenterId = "";
  formData.routingAllocationId = "";
  if (id) {
    const { data } = await getWorkShopsApi(id);
    workShopList.value = data;
  } else {
    workShopList.value = [];
  }
};

// 获取周列表
const monthOptions = ref<OptionType[]>();

// 年度变更重新获取月份
function selectYear(e: number) {
  if (e) {
    formData.planWeek = "";
    monthOptions.value = getMonthList(e);
  } else {
    monthOptions.value = [];
    formData.planWeek = "";
  }
}

function selectWorkCenter(e: string) {
  formData.routingAllocationId = "";
  if (e) {
    getMaterialList();
  } else {
    materialList.value = [];
  }
}

const materialList: any = ref([]);
async function getMaterialList() {
  const { data } = await request({
    url: "/mes/mesroutingallocation/queryList",
    method: "post",
    data: {
      workCenterId: formData.workCenterId,
      plantId: formData.plantId,
    },
  });
  materialList.value = data;
}

onMounted(async () => {
  // 获取周搜索列表
  const currentYear = new Date().getFullYear(); // 当前年份
  monthOptions.value = getMonthList(currentYear);
});

const isReadonly = ref(false);
/** 弹窗显示隐藏 */
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal && props.title.includes("查看")) {
      isReadonly.value = true;
    } else {
      isReadonly.value = false;
    }
  }
);

/** 定义form信息 */
const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  workCenterId: [
    { required: true, message: "请选择工作中心", trigger: "change" },
  ],
  planYear: [{ required: true, message: "请选择工作年份", trigger: "change" }],
  planWeek: [{ required: true, message: "请选择工作周", trigger: "change" }],
  routingAllocationId: [
    { required: true, message: "请选择物料/版本号", trigger: "change" },
  ],
  planBatch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
    { max: 50, message: "生产批次不能超过50个字符", trigger: "blur" },
  ],
  planQuantity: [
    { required: true, message: "请输入计划数量", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive(JSON.parse(JSON.stringify(getOneLineDate())));

/** 删除行 */
const handleDelete = (index: any) => {
  formData.plans.splice(index, 1);
};

/** 添加行 */
const handleAdd = () => {
  // formData.plans.push(JSON.parse(JSON.stringify(onePlan)));
};

/** 编辑赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    // Object.assign(formData, newVal);
    if (newVal?.id) {
      const {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        version,
        versionNo,
        planState,
        planQuantity,
        planBatch,
        workCenterCode,
        workCenterId,
        planYear,
        planWeek,
        routingAllocationId,
        requestPlanList,
      } = newVal;
      Object.assign(formData, {
        id,
        plantId,
        plantCode,
        materialId,
        materialCode,
        version,
        versionNo,
        planState,
        planQuantity,
        planBatch,
        workCenterCode,
        workCenterId,
        planYear,
        planWeek,
        routingAllocationId,
        requestPlanList,
      });
      formData.yield = newVal.yield;

      if (plantId) {
        const { data } = await getWorkShopsApi(plantId);
        workShopList.value = data;
      }
      if (plantId && workCenterId) {
        formDatagetMaterialList();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  Object.assign(formData, { ...JSON.parse(JSON.stringify(getOneLineDate())) });
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: formData.id
          ? "/system/oakeyworktask/update"
          : "/mes/mesproduceorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`${text}成功`);
      emit("reset-table", formData.id || "");
      closeDialog();
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px;
}
.el-form {
  position: relative;
  .formCover {
    position: absolute;
    top: 0;
    width: 100%;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 2000;
    cursor: default;
  }
  .el-select {
    width: 100%;
  }
}
.produce_order_form {
  :deep(.el-form-item) {
    margin-bottom: 16px !important;
  }
  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .title {
      color: #333;
      font-size: 15px;
      font-weight: 600;
      line-height: 30px;
    }
  }
}
</style>
